import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import styled from 'styled-components';
import BaseModal from 'component/Modals/BaseModal';
import Button from 'widget/Button';
import ReactCrop from 'react-image-crop';
import 'react-image-crop/dist/ReactCrop.css';
import { SkyBlue, White } from 'style/Color';

const Badge = styled.div`
  display: flex;
  align-items: center;
  justify-content: space-between;
`;

const GrayDashed = styled.div`
  height: 200px;
  display: flex;
  align-items: center;
  justify-content: center;
  border: dashed 4px ${White};
  background-color: ${SkyBlue};
`;

const Cloumn = styled.div`
  display: flex;
  align-items: center;
  justify-content: center;
`;

const Item = styled.div`
  flex: 1;
  width: 100%;
  text-align: center;
`;

const FooterBadge = styled(Badge)`
  height: 56px;
  display: flex;
  padding: 10px 0;
  justify-content: center;
`;

class UploadModal extends PureComponent {
  state = {
    src: null,
    crop: {
      unit: '%',
      width: 30,
      aspect: 1 / 1
    }
  };

  onSelectFile = e => {
    if (e.target.files && e.target.files.length > 0) {
      const reader = new FileReader();
      reader.addEventListener('load', () => this.setState({ src: reader.result }));
      reader.readAsDataURL(e.target.files[0]);
    }
  };

  // If you setState the crop in here you should return false.
  onImageLoaded = image => {
    this.imageRef = image;
  };

  onCropComplete = crop => {
    this.makeClientCrop(crop);
  };

  onCropChange = crop => {
    this.setState({ crop });
  };

  getCroppedImg(image, crop, fileName) {
    const canvas = document.createElement('canvas');
    const scaleX = image.naturalWidth / image.width;
    const scaleY = image.naturalHeight / image.height;
    canvas.width = crop.width;
    canvas.height = crop.height;
    const ctx = canvas.getContext('2d');

    ctx.drawImage(
      image,
      crop.x * scaleX,
      crop.y * scaleY,
      crop.width * scaleX,
      crop.height * scaleY,
      0,
      0,
      crop.width,
      crop.height
    );

    return new Promise((resolve, reject) => {
      canvas.toBlob(b => {
        if (!b) {
          reject(new Error('Canvas is empty'));
          console.error('Canvas is empty');
          return;
        }
        const blob = b;
        this.blob = blob;
        blob.name = fileName;
        window.URL.revokeObjectURL(this.fileUrl);
        this.fileUrl = window.URL.createObjectURL(blob);
        resolve(this.fileUrl);
      }, 'image/jpeg');
    });
  }

  handleClick = () => {
    this.props.onSubmit(this.blob);
  };

  async makeClientCrop(crop) {
    if (this.imageRef && crop.width && crop.height) {
      const croppedImageUrl = await this.getCroppedImg(this.imageRef, crop, 'newFile.jpeg');
      this.setState({ croppedImageUrl });
    }
  }

  inputRef = React.createRef();

  render() {
    const { crop, src, croppedImageUrl } = this.state;
    const ready = !src && !croppedImageUrl;
    return (
      <BaseModal onClose={this.props.onClose}>
        {ready ? (
          <GrayDashed>
            <Button
              role="textbox"
              theme="primary"
              bold
              onClick={() => this.inputRef.current.click()}
            >
              Upload An Image
            </Button>
            <input
              ref={this.inputRef}
              style={{ display: 'none' }}
              type="file"
              accept="image/*"
              onChange={this.onSelectFile}
            />
          </GrayDashed>
        ) : (
          [
            <Cloumn key="crop">
              <Item>
                <ReactCrop
                  src={src}
                  crop={crop}
                  ruleOfThirds
                  onImageLoaded={this.onImageLoaded}
                  onComplete={this.onCropComplete}
                  onChange={this.onCropChange}
                />
              </Item>
              {/* <Item>
              {croppedImageUrl && <img alt="Crop" style={{ width: '100%' }} src={croppedImageUrl} />}
            </Item> */}
            </Cloumn>,
            <FooterBadge key="foot">
              <Button theme="primary" bold onClick={this.handleClick}>
                Submit
              </Button>
            </FooterBadge>
          ]
        )}
      </BaseModal>
    );
  }
}

UploadModal.propTypes = {
  onClose: PropTypes.func.isRequired,
  onSubmit: PropTypes.func.isRequired
  // eslint-disable-next-line react/forbid-prop-types
  // data: PropTypes.object.isRequired
};

export default UploadModal;
